package com.cqeec.gams.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.cqeec.gams.entity.Account;
import com.cqeec.gams.entity.FunctionalModule;
import com.cqeec.gams.entity.Role;
import com.cqeec.gams.entity.RolePermission;
import com.cqeec.gams.model.Function;
import com.cqeec.gams.service.FunctionalModuleService;
import com.cqeec.gams.service.RoleService;

@Controller
@RequestMapping("/app/role/")
public class RoleController {
	@Autowired
	private RoleService roleService;

	@Autowired
	private FunctionalModuleService fmService;

	@RequestMapping("/save.html")
	public String save(RedirectAttributes redirectAttributes, Role role, String[] function, HttpSession session) {
		// 数据验证
		// 保存数据
		String url;
		Object obj = session.getAttribute("user");
		if (obj == null) {
			url = "redirect:/login.html";
		} else {
			Account account = (Account) obj;

			String roleId = role.getId();
			if (roleId == null || "".equals(roleId)) {
				// 角色没有ID，表示新增
				role.setCreator(account.getId());
				role.setCreatorName(account.getName());
				role.setCreationTime(new Date());
				url = "redirect:/app/role/add.html";
			} else {
				// 有ID，表示修改
				role.setLastUpdater(account.getId());
				role.setLastUpdaterName(account.getName());
				role.setCreator(account.getId());
				role.setCreatorName(account.getName());
				url = "redirect:/app/role/edit/" + role.getId();
			}
			try {
				roleService.save(role, function);
				redirectAttributes.addFlashAttribute("code", 0);
				redirectAttributes.addFlashAttribute("message", "保存数据成功！");
			} catch (Exception ex) {
				ex.printStackTrace();
				redirectAttributes.addFlashAttribute("code", 1);
				redirectAttributes.addFlashAttribute("message", "保存数据失败！");
				redirectAttributes.addFlashAttribute("obj", role);
			}
		}
		return url;
	}

	@RequestMapping("/index.html")
	public ModelAndView gotoListPage(String name, String page) {
		// 从数据库中将数据读取出来传到页面显示
		// 控制器->服务->Mapper->数据库，以及在控制器、服务和Mapper通用的实体类
		ModelAndView mav = new ModelAndView("role/list");
		// mav.addObject("list", roleService.findAll());
		int pageNumber, pageSize;
		if (page == null || "".equals(page)) {
			pageNumber = 1;
		} else {
			pageNumber = Integer.parseInt(page);
		}
		pageSize = 10;

		long total = roleService.count(name);
		long pages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
		if (pageNumber > pages) {
			pageNumber = 1;
		}
		List<Role> list = roleService.page(name, pageNumber, pageSize);
		mav.addObject("page", pageNumber);
		mav.addObject("size", pageSize);
		mav.addObject("total", total);
		mav.addObject("pages", pages);
		mav.addObject("list", list);
		mav.addObject("name", name);
		return mav;
	}

	@RequestMapping("/add.html")
	public String gotoAddPage(Model model) {
		List<Function> functions = fmService.getAllFunction();
		model.addAttribute("functions", functions);
		return "role/add";
	}

	@RequestMapping("/edit/{id}")
	public String gotoEditPage(Model model, @PathVariable String id) {
		// 查询系统所有的功能模块
		List<Function> functions = fmService.getAllFunction();
		model.addAttribute("functions", functions);
		// 根据角色ID查找角色
		Role role = roleService.get(id);
		model.addAttribute("obj", role);
		// 查找角色已经拥有的功能模块
		List<RolePermission> list = roleService.getRolePermission(id);
		List<String> havePermission = new ArrayList<String>();
		for (RolePermission rp : list) {
			havePermission.add(rp.getFunctionalModule());
		}
		for (Function f : functions) {
			if (havePermission.contains(f.getFunctionGroupId())) {
				f.setSelected(true);
			}
			List<FunctionalModule> functionModules = f.getFunctionModules();
			for (FunctionalModule fm : functionModules) {
				if (havePermission.contains(fm.getId())) {
					fm.setSelected(true);
				}
			}
		}
		return "role/edit";
	}
}
